<!-- 复制组件 -->
<template>
  <el-button link :style="style" @click="handleClipboard">
    <slot>
      <el-icon color="var(--el-color-primary)">
        <Check v-if="copySuccess" />
        <CopyDocument v-else />
      </el-icon>
    </slot>
  </el-button>
</template>

<script setup lang="ts">
import { isString } from 'lodash-es';

defineOptions({
  name: 'CopyButton',
  inheritAttrs: false,
});

const props = defineProps({
  text: {
    type: [String, Number],
    default: '',
  },
  style: {
    type: Object,
    default: () => ({}),
  },
});

const copySuccess = ref(false);

const successCallback = () => {
  copySuccess.value = true;
  useTimeoutFn(() => {
    copySuccess.value = false;
  }, 2000);
};

function handleClipboard() {
  if (copySuccess.value) return;
  const textStr = isString(props.text) ? props.text : String(props.text);
  if (navigator.clipboard && navigator.clipboard.writeText) {
    // 使用 Clipboard API
    navigator.clipboard
      .writeText(textStr)
      .then(() => {
        // ElMessage.success({
        //   message: 'Copy successfully.',
        //   grouping: true,
        // });
        successCallback();
      })
      .catch((error) => {
        ElMessage.warning({
          message: 'Copy failed!',
          grouping: true,
        });
        console.log('[CopyButton] Copy failed', error);
      });
  } else {
    // 兼容性处理（useClipboard 有兼容性问题）
    const input = document.createElement('input');
    input.style.position = 'absolute';
    input.style.left = '-9999px';
    input.setAttribute('value', textStr);
    document.body.appendChild(input);
    input.select();
    try {
      const successful = document.execCommand('copy');
      if (successful) {
        // ElMessage.success({
        //   message: 'Copy successfully.',
        //   grouping: true,
        // });
        successCallback();
      } else {
        ElMessage.warning({
          message: 'Copy failed!',
          grouping: true,
        });
      }
    } catch (err) {
      ElMessage.error({
        message: 'Copy failed!',
        grouping: true,
      });
      console.log('[CopyButton] Copy failed!', err);
    } finally {
      document.body.removeChild(input);
    }
  }
}
</script>
